package com.homework;

import java.io.*;
import java.util.Vector;

public class Recorder {
    private static int allEnemyTankNum = 0;
    //    private static BufferedWriter bw=null;
//    public static BufferedReader br=null;
    private static ObjectOutputStream oos = null;
    private static ObjectInputStream ois = null;
    private static String path = "recorder.dat";
    private static Vector<EnemyTank> enemyTanks = null;
    private static Hero hero = null;
    private static Vector<Node> nodes = new Vector<>();
    public static void setHero(Hero hero) {
        Recorder.hero = hero;
    }

    public static void keepRecord() {
//            bw=new BufferedWriter(new FileWriter(path));
//            bw.write(allEnemyTankNum+"\r\n");
//            for (int i=0;i<enemyTanks.size();i++){
//                EnemyTank enemyTank = enemyTanks.get(i);
//                bw.write(enemyTank.getX()+" "+ enemyTank.getY()+" "+" "+enemyTank.getDirection()+"\r\n");
//            }
        try {
            oos = new ObjectOutputStream(new FileOutputStream(path));
            oos.writeInt(allEnemyTankNum);
            for (int i = 0; i < enemyTanks.size(); i++) {
                EnemyTank e = enemyTanks.get(i);
                oos.writeObject(new Node(e.getX(), e.getY(), e.getDirection()));
            }
            oos.writeObject(new Node(hero.getX(), hero.getY(), hero.getDirection()));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static Vector<Node> readRecord() {
        if (!new File(path).exists()) {
            System.out.println("不存在上局游戏");
            System.exit(0);
        }
        try {//或者使用BufferedReader 用String[] xyd=line.split(" ")分割
            ois = new ObjectInputStream(new FileInputStream(path));
            allEnemyTankNum = ois.readInt();
            while (true){
                Node e = (Node) ois.readObject();//读到末尾不会返回什么null或者-1
                nodes.add(e);
            }
        } catch (IOException | ClassNotFoundException e) {//此处readObject会抛出异常不用管 用异常判断读到末尾

        } finally {
            try {
                if (ois != null)
                    ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return nodes;
    }

    public static Vector<EnemyTank> getEnemyTanks() {
        return enemyTanks;
    }

    public static void setEnemyTanks(Vector<EnemyTank> enemyTanks) {
        Recorder.enemyTanks = enemyTanks;
    }

    public static int getAllEnemyTankNum() {
        return allEnemyTankNum;
    }

    public static void addAllEnemyTankNum() {
        allEnemyTankNum++;
    }
}
